package models

import (
	"fmt"
	"geek_go/lecture4/config"
	"geek_go/lecture4/internal/logger"
	"github.com/go-xorm/xorm"
	"gopkg.in/macaron.v1"
	"strings"
	"time"
	"xorm.io/core"
)

type Status int8
type CommonMap map[string]interface{}

var TablePrefix = ""

const (
	Page        = 1    // 当前页数
	PageSize    = 20   // 每页多少条数据
	MaxPageSize = 1000 // 每次最多取多少条
)

const DefaultTimeFormat = "2006-01-02 15:04:05"

const (
	dbPingInterval = 90 * time.Second
	dbMaxLiftTime  = 2 * time.Hour
)

type Model struct {
	config *config.Config
	Db     *xorm.Engine
}

func NewModel(c *config.Config) *Model {
	return &Model{
		config: c,
		Db:     CreateDb(c),
	}
}

// 创建Db
func CreateDb(config *config.Config) *xorm.Engine {
	dsn := getDbEngineDSN(config)
	engine, err := xorm.NewEngine(config.Db.Engine, dsn)
	if err != nil {
		logger.Fatal("创建xorm引擎失败", err)
	}
	engine.SetMaxIdleConns(config.Db.MaxIdleConns)
	engine.SetMaxOpenConns(config.Db.MaxOpenConns)
	engine.SetConnMaxLifetime(dbMaxLiftTime)

	if config.Db.Prefix != "" {
		// 设置表前缀
		TablePrefix = config.Db.Prefix
		mapper := core.NewPrefixMapper(core.SnakeMapper{}, config.Db.Prefix)
		engine.SetTableMapper(mapper)
	}
	// 本地环境开启日志
	if macaron.Env == macaron.DEV {
		engine.ShowSQL(true)
		engine.Logger().SetLevel(core.LOG_DEBUG)
	}

	return engine
}

// 获取数据库引擎DSN  mysql,sqlite,postgres
func getDbEngineDSN(config *config.Config) string {
	engine := strings.ToLower(config.Db.Engine)
	dsn := ""
	switch engine {
	case "mysql":
		dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&allowNativePasswords=true",
			config.Db.User,
			config.Db.Password,
			config.Db.Host,
			config.Db.Port,
			config.Db.Database,
			config.Db.Charset)
	case "postgres":
		dsn = fmt.Sprintf("user=%s password=%s host=%s port=%d dbname=%s sslmode=disable",
			config.Db.User,
			config.Db.Password,
			config.Db.Host,
			config.Db.Port,
			config.Db.Database)
	}
	return dsn
}
